package com.app.controller;


import com.app.service.CustomUserDetailsService;
import com.app.utils.ApiResponse;
import com.app.utils.JwtUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.bind.annotation.*;

/**
 * @Author: cn
 * @Description: TODO
 * @Date: 2025/7/12 11:19
 * @Version: 1.0
 */
@RestController
@RequestMapping("/api/auth")
public class TestController {
    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private CustomUserDetailsService customUserDetailsService;

    /**
     * 用户认证接口
     *获取到对应的接口
     * @param username
     * @param password
     * @return
     */
    @PostMapping("/login")
    public ResponseEntity<?> login(@RequestParam("username") String username, @RequestParam("password") String password) {
        try {
            // 使用 AuthenticationManager 进行用户验证
            Authentication authenticate = authenticationManager.authenticate(
                    new UsernamePasswordAuthenticationToken(username, password)
            );
            // 通过认证后，获取用户详情并生成JWT Token
            final UserDetails userDetails = customUserDetailsService.loadUserByUsername(username);
            final String jwt = jwtUtil.generateToken(userDetails);

            // 如果验证成功，可以根据需要生成 JWT Token 或其他形式的凭证
            return ResponseEntity.ok(new ApiResponse(200, "success", jwt));
        } catch (BadCredentialsException ex) {
            // 如果验证失败，返回错误信息
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("Invalid username or password");
        }
    }
}
